/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */



import IAutoSearch from '@/components/soa/IAutoSearch';
import { useRequest, useAntdTable } from 'ahooks';
import {
  Col,
  Form,
  Input,
  Row,
  Space,
  Modal,
  Tooltip,
  Select,
  message,
  TableColumnsType,
  Button,
} from 'antd';
import { useState } from 'react';
import React from 'react';
import styles from './index.less';
import {getDateMinute, getDateTime} from '@/utils/soa/utils';
import IAutoButton from '@/components/soa/IAutoButton';
// import IAutoSearchInput from '@/components/soa/IAutoSearchInput';
import IAutoTable from '@/components/soa/IAutoTable';
import { router } from 'umi';
import IAutoPage from '@/components/soa/IAutoPage';
import { getSceneAuditList, scenesAudit, getVehicleVinList, scenesTestRelease } from '@/services/soa/sceneAudit';
import { ISceneAuditItem, ISceneAuditListParams } from '@/types/sceneAudit';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import SceneBlock from '@/components/SceneBlock';
import moment from "moment";

const { Option } = Select;
const { Item, useForm } = Form;
const { TextArea } = Input;

enum statusTypes {
  '上架审核中',
  '下架审核中',
  '上架成功',
  '上架失败',
  '下架成功',
  '下架失败',
  '定时上架中',
}
enum statusPlease {
  '上架申请',
  '下架申请',
}
enum releaseTypes {
  '定时发布',
  '立即发布',
}
const Audit = (props: any) => {
  const {
    location: { pathname },
  } = props;
  const [form] = useForm();
  const [refuseForm] = useForm();
  const [testForm] = useForm();
  const [isVisible, setIsVisible] = useState(false);
  const [isTestModalOpen, setIsTestModalOpen] = useState(false);
  const [isTestModalTitle, setIsTestModalTitle] = useState(String);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ISceneAuditItem>({});
  const [thingsValue, setThingsValue] = useState(6);
  //列表渲染
  const { tableProps, refresh, search } = useAntdTable(getSceneAuditList, {
    form,
  });
  const { submit } = search;

  const auditRequest = useRequest(scenesAudit, {
    manual: true,
    onSuccess: (response, params) => {
      if (response.statusCode === '0') {
        if (params[0].auditResult) {
          //同意
          if (params[0].auditStatus == 1) {
            message.success('上架成功！');
          } else if (params[0].auditStatus == 2) {
            message.success('下架成功！');
          }
        } else {
          //拒绝
          if (params[0].auditStatus == 1) {
            message.success('已拒绝申请！');
          } else if (params[0].auditStatus == 2) {
            message.success('已拒绝申请！');
          }
        }
      }
      handleCancel();
      refresh();
    },
  });

  const confirmRefuse = (record: any) => {
    setCurrentRecord(record);
    setIsVisible(true);
  };

  const confirmTestRelease = (record: any) => {
    testForm.setFieldsValue({
      sceneRecordUuid: record.sceneRecordUuid,
    });
    setIsTestModalTitle(record.name)
    setIsTestModalOpen(true);
  };

  const handleOk = () => {
    refuseForm.submit();
  };
  const handleCancel = () => {
    refuseForm.resetFields();
    setIsVisible(false);
  };
  const handlePreviewCancel = () => {
    setPreviewVisible(false);
  }

  const handleTestCancel =() => {
    testForm.resetFields();
    setIsTestModalOpen(false);
  }

  const handleTestConfirm =() => {

   scenesTestReleaseRequest.run({sceneRecordUuid: testForm.getFieldValue('sceneRecordUuid'), vinList: testForm.getFieldValue('vinList')})
  }
  const otherThings = (value: any) => {
    form.setFieldsValue({
      auditStatus: [value === 6 ? null : value],
    });
    setThingsValue(value);
  };

  //表单提交
  const onFinish = (values: any) => {
    const { sceneRecordUuid, auditStatus: status } = currentRecord;
    const data: ISceneAuditListParams = {
      auditStatus: status == 0 ? 1 : 2,
      rejectReason: values.rejectReason,
      auditResult: 0,
    };
    auditRequest.run(data, sceneRecordUuid);
  };

  // 同意
  const confirmAgree = (record: any) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      className: 'title',
      content: record?.auditStatus == 0 ? `是否确认同意上架?` : `是否确认同意下架?`,
      onOk() {
        auditRequest.run(
          { auditResult: 1, auditStatus: record?.auditStatus == 0 ? 1 : 2 },
          record.sceneRecordUuid,
        );
      },
    });
  };

      // 主动
  const soldoutAgree = (record: any) => {
    Modal.confirm({
      icon: <ExclamationCircleOutlined />,
      className: 'title',
      content: `是否确认下架?`,
      onOk() {
        auditRequest.run({ auditResult: 1, auditStatus: 2 }, record.sceneRecordUuid);
      },

    });
  };
  // 查看和编辑
  const goDetail = (sceneRecordUuid: string) => {
    router.push('/soaManage/scene/audit/scene_detail?sceneRecordUuid=' + sceneRecordUuid);
  };

  const goDetail1 = (sceneRecordUuid: string, name: string) => {
    router.push({
      pathname: '/soaManage/scene/audit/scene_edit_detail',
      query: {
        name: name,
        sceneRecordUuid: sceneRecordUuid,
      },
    });
  };


  const vehicleVinList = useRequest(getVehicleVinList);

  const scenesTestReleaseRequest = useRequest(scenesTestRelease, {
    manual: true,
    onSuccess: (response) => {
      if (response.statusCode === '0') {
        message.success('下发成功！');
      }
      handleTestCancel();
      refresh();
    },
  });

  const handleVinChange = (values: string[]) => {
    testForm.setFieldsValue({
      vinList: values
    })
  }

  // 场景预览
  const toPreview = (record: ISceneAuditItem) => {
    console.log("� ~ file: index.tsx ~ line 175 ~ toPreview ~ record", record)
    // todo 缺少字段 seriesCode modelCode sceneUuid
    setCurrentRecord(record);
    setPreviewVisible(true);
  }

  // 列表
  const columns: TableColumnsType<ISceneAuditItem> = [
    {
      title: '场景名',
      dataIndex: 'name',
      width: 180,
      ellipsis: true,
      render: (_, record) => {
        return (
          <Button type='link' onClick={() => toPreview(record)}>{_}</Button>
        );
      },
    },
    {
      title: '分类名称',
      dataIndex: 'categoryName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '车系',
      dataIndex: 'seriesName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '车型',
      dataIndex: 'modelName',
      width: 250,
      ellipsis: true,
      render: (_, { modelName }) => {
        return (
          <Tooltip title={modelName}>
            <span className={styles.reasonSpan}>{modelName}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '申请事由',
      dataIndex: 'auditStatus',
      width: 100,
      render: (_, record) => <span>{statusPlease[record.auditStatus]}</span>,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      width: 180,
      render: (text) => getDateTime(text),
    },
    {
      title: '期望发布时间',
      dataIndex: 'cronReleaseTime',
      width: 180,
      ellipsis: true,
      render: (_, { cronReleaseTime: time}) => {
        if (time === null) {
          return <span>立即发布</span>
        } else {
          return getDateMinute(time)
        }
      },
    },
    {
      title: '状态',
      width: 180,
      dataIndex: 'auditStatus',
      render: (_, { auditStatus, rejectReason }) => {
        if (auditStatus == 3 || auditStatus == 5) {
          return (
            <div>
              <div style={{ color: '#ff7918' }}>{statusTypes[auditStatus]}</div>
              <div className={styles.reasonBox}>
                <Tooltip title={rejectReason}>
                  <span className={styles.reasonSpan}>原因：{rejectReason}</span>
                </Tooltip>
              </div>
            </div>
          );
        } else if (auditStatus == 0 || auditStatus == 1) {
          return <div style={{ color: '#3569fd' }}>{statusTypes[auditStatus]}</div>;
        } else {
          return <div style={{ color: '#00a870' }}>{statusTypes[auditStatus]}</div>;
        }
      },
    },
    {
      title: '操作',
      fixed: 'right',
      key: 'operation',
      width: 350,
      render: (_, record) => {
        const isCronTimePassed = record.cronReleaseTime != null && moment(record.cronReleaseTime).isBefore(moment());
        if (record.auditStatus == 0 || record.auditStatus == 1) {
          return (
            <Space size="middle">
              <IAutoButton
                onClick={() => goDetail(record.sceneRecordUuid)}
                pathname={pathname}
                auth={'audit_doDetail'}
              >
                查看
              </IAutoButton>
              {record.auditStatus == 0 && (
                <IAutoButton
                  onClick={() => goDetail1(record.sceneRecordUuid, record.name)}
                  pathname={pathname}
                  auth={'audit_doDEdit'}
                >
                  编辑
                </IAutoButton>
              )}
              <IAutoButton
                onClick={() => confirmAgree(record)}
                pathname={pathname}
                auth={'audit_doAgree'}
		disabled={isCronTimePassed}
              >
                同意
              </IAutoButton>
              <IAutoButton
                onClick={() => confirmRefuse(record)}
                pathname={pathname}
                auth={'audit_doRefuse'}
              >
                拒绝
              </IAutoButton>
	      
              <IAutoButton onClick={() => confirmTestRelease(record)} pathname={pathname} auth={"audit_doDetail"}>下发测试</IAutoButton>
            </Space>
          )
        }else if(record.auditStatus == 2){

          return(
            <Space size="middle">
              <IAutoButton onClick={() => goDetail(record.sceneRecordUuid)} pathname={pathname} auth={"audit_doDetail"}>查看</IAutoButton>
              <IAutoButton onClick={() => soldoutAgree(record)} pathname={pathname} auth={"audit_doAgree"}>下架</IAutoButton>
              <IAutoButton onClick={() => confirmTestRelease(record)} pathname={pathname} auth={"audit_doDetail"}>下发测试</IAutoButton>
            </Space>
          )
        }
        else {
          return(
            <Space size="middle">
              <IAutoButton
                onClick={() => goDetail(record.sceneRecordUuid)}
                pathname={pathname}
                auth={'audit_doDetail'}
              >
                查看
              </IAutoButton>
	      
              <IAutoButton onClick={() => confirmTestRelease(record)} pathname={pathname} auth={"audit_doDetail"}>下发测试</IAutoButton>
            </Space>
          );
        }
      },
    },
  ];

  // 默认item布局
  const defaultItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };
  // 默认无label表单布局
  const defaultLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
    },
  };

  return (
    <div className={styles.main}>
      <IAutoSearch>
        <Row gutter={[8, 8]}>
          <Col sm={22} xs={24} style={{ display: 'flex', justifyContent: 'stretch' }}>
            <Form form={form} layout={'inline'}>
              <Item {...defaultLayoutWithOutLabel} name="name" style={{ marginBottom: '8px' }}>
                {/*<IAutoSearchInput submit={submit} placeholder="请输入场景名称进行检索" />*/}
                <Input placeholder="请输入场景名称进行检索" allowClear maxLength={20} />
              </Item>

              <Item {...defaultItemLayout} label="申请事由" style={{ marginBottom: '8px' }}>
                <Select
                  allowClear
                  className={styles.select}
                  defaultValue={6}
                  onChange={otherThings}
                >
                  <Option value={6}>全部</Option>
                  <Option value={0}>上架申请</Option>
                  <Option value={1}>下架申请</Option>
                </Select>
              </Item>

              <Item {...defaultItemLayout} label="场景状态" name="auditStatus">
                {thingsValue === 6 ? (
                  <Select className={styles.select} defaultValue={'全部'}>
                    <Option>全部</Option>
                    <Option value={0}>上架审核中</Option>
                    <Option value={1}>下架审核中</Option>
                    <Option value={2}>上架成功</Option>
                    <Option value={3}>上架失败</Option>
                    <Option value={4}>下架成功</Option>
                    <Option value={5}>下架失败</Option>
                    <Option value={6}>定时上架中</Option>
                  </Select>
                ) : thingsValue === 0 ? (
                  <Select className={styles.select}>
                    <Option value={0}>上架审核中</Option>
                    <Option value={2}>上架成功</Option>
                    <Option value={3}>上架失败</Option>
                  </Select>
                ) : (
                  <Select className={styles.select}>
                    <Option value={1}>下架审核中</Option>
                    <Option value={4}>下架成功</Option>
                    <Option value={5}>下架失败</Option>
                  </Select>
                )}
              </Item>
            </Form>
          </Col>
          <Col xs={24} sm={2} style={{ display: 'flex', alignItems: 'end' }}>
            <IAutoButton
              style={{ marginBottom: '8px' }}
              type={'primary'}
              onClick={submit}
              buttonType={'form'}
              pathname={pathname}
              auth={'audit_doSearch'}
            >
              查询
            </IAutoButton>
          </Col>
        </Row>
      </IAutoSearch>

      <IAutoPage>
        <IAutoTable rowKey="scenarioUid" columns={columns} tableProps={tableProps} />
      </IAutoPage>

      <Modal title="拒绝原因" visible={isVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name="refuseForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
          form={refuseForm}
          onFinish={onFinish}
        >
          <Item
            label="请填写"
            name="rejectReason"
            rules={[
              { required: true, message: '请输入至少五个字符' },
              { min: 5, message: '请输入至少五个字符' },
            ]}
          >
            <TextArea minLength={5} rows={5} placeholder="请输入至少五个字符" maxLength={255} />
          </Item>
        </Form>
      </Modal>

      <Modal
          title={isTestModalTitle}
          visible={isTestModalOpen}
          onCancel={handleTestCancel}
          onOk={handleTestConfirm}
          okText="发布(所选)"
        >
          <Form name="testForm" form={testForm}  colon={true}>
            <Item
              label="输入VIN码"
              name="vehicleVin"
            >
              <Select
                mode="multiple"
                showArrow
                placeholder={'请选择车辆VIN码'}
                onChange={handleVinChange}
                allowClear
              >
                {vehicleVinList?.data?.data?.map?.((obj: any) => (
                  <Option value={obj.vin} key={obj.vin}>
                    {obj.vin}
                  </Option>
                ))}
              </Select>
            </Item>
          </Form>
        </Modal>

      <Modal
        wrapClassName='sceneBlockModal'
        maskClosable={false}
        destroyOnClose
        title={currentRecord?.name || "预览场景"}
        visible={previewVisible}
        footer={null}
        onCancel={handlePreviewCancel}
        width='70vw'
      >
        <div style={{width:"100%"}}>
          <SceneBlock
            fileUuid={currentRecord.sceneFileUuid}
            seriesCode={currentRecord.seriesCode}
            modelCode={currentRecord.modelCode}
            socVersion={currentRecord.serviceMatrixVersion}
            onClose={handlePreviewCancel}
          />
        </div>
      </Modal>
    </div>
  );
};

export default Audit;
